﻿using System;
using Cubicle.Core.Interfaces;
using Cubicle.Core.Processors;
using Cubicle.Excel.Functions;
using Cubicle.Excel.Shared;

namespace Cubicle.Excel.Hosting
{
    public class AppDomainProxy : LocalProxy, IDisposable
    {

        public AppDomainProxy(string alias, Processor<object> marshalQueue)
            : base(alias, marshalQueue, null)
        {
            var appBasePath = GeneralFunctions.XllPath();
            Domain = AppDomain.CreateDomain(alias, null, appBasePath, "", true);
            var targetType = typeof(RemoteFactory);
            var factory = (RemoteFactory)Domain.CreateInstanceAndUnwrap(targetType.Assembly.FullName, targetType.FullName);
            Proxy = factory.CreateRemoteEngine();
        }

        public AppDomain Domain { get; private set; }

        public override bool IsConnected()
        {
            try   { return Id != null; } 
            catch { return false; }
        }

        public override IRObject Remove(string handle)
        {
            Proxy.RemoveHandle(handle);
            return null;
        }

        public override object GetProxy(string handle)
        {
            object result = Proxy.Get(handle);
            return ExcelHelpers.JaggedToDouble(result);
        }

        public override IRObject GetRObject(string handle)
        {
            return null;
        }

        public override string LoadAssembly(byte[] assembly, byte[] symbols = null)
        {
            return Proxy.LoadAssembly(assembly, symbols);
        }

        public void Dispose()
        {
            if (Domain != null) AppDomain.Unload(Domain);
        }

    }
}